package com.example.coupon.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author wangbo
 * @description:
 * @date 2021/1/2916:49
 */
@Component
@Slf4j
public class AccessLogFilter extends AbstractPostZuulFilter{

    @Override
    protected Object cRun() {
        HttpServletRequest request = context.getRequest();;
        //从PreRequestFilter中获取设置的请求时间戳
        Long startTime = (Long) context.get("startTime");
        String uri = request.getRequestURI();
        long duration = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() - startTime;

        //从网关通过的请求都会打印日志记录：uri+duration
        log.info("uri:{},duration:{}",uri,duration);
        return success();
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1;
    }
}
